// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

/****
 *
 *判断账号密码是否匹配
 */
// 扩展 HttpServlet 类
public class myTest extends HttpServlet{

    private String message;

    public void init() throws ServletException
    {
        //
        // 执行必需的初始化
        message = "Hello World";
    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
            throws ServletException, IOException
    {
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setContentType("text/json; charset=utf-8");
        PrintWriter out = response.getWriter();

        try {
            //写数据库访问
            Class.forName("com.mysql.jdbc.Driver");
            Connection connect = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/ListSystem", "root", "");
            Statement stmt = connect.createStatement(); //创建Statement对象
            String sql;
            sql = "SELECT * FROM User_t";
//            ResultSet rs =
            ResultSet rs = stmt.executeQuery(sql);
                response.setCharacterEncoding("UTF-8");//setContentType与setCharacterEncoding的顺序不能调换，否则还是无法解决中文乱码的问
                String account = request.getParameter("account");
                String password = request.getParameter("password");
//                HttpSession session = request.getSession();
                String answer = "0";
            while (rs.next()) {
                if (rs.getString(1).equals(account)&&rs.getString(3).equals(password)){
//                    out.println(rs.getString(4));
                    request.getSession().setAttribute("ID",account);

                    if (rs.getString(4).equals("教师")){
                        answer = "1";
                    } else if (rs.getString(4).equals("学生")){
                        answer = "2";
                    }else {
                        answer = "3";
                    }

                }
            }
            out.write(answer);
            out.close();
            // 输出数据
            // 完成后关闭
            rs.close();
            stmt.close();
            connect.close();
        }catch (Exception e) {
            out.print("get data error!");
            e.printStackTrace();
                }
        System.out.println((String) request.getSession().getAttribute("ID"));

    }

    public void destroy()
    {
        // 什么也不做
    }
}